package com.balance.anole.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.balance.anole.business.to.BusinessDateTO;

public class UploadDownloadUtil {

	private Properties configProp;
	private static UploadDownloadUtil instance = null;

	private static final String CONFIG_FILE_NAME = "download_upload.properties";

	private String appPath = "";

	private static final String DATA_FOLDER_KEY = "data_folder";

	private UploadDownloadUtil(){
		configProp = new Properties();
		appPath = new File("").getAbsolutePath().replace("\\", "/");

	}

	private void createDataDirectory(){
		File dataDir = new File(appPath + "/" + getConfigValueByKey(DATA_FOLDER_KEY));
		if( !dataDir.exists() || !dataDir.isDirectory()){
			dataDir.mkdir();
		}
	}

	private void loadProperties() throws Exception{
		InputStream is = UploadDownloadUtil.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME);
		if(is != null){
			try {
				configProp.load(is);
			} catch (IOException e) {
				throw new Exception("Error loading configuration file: " + CONFIG_FILE_NAME);
			}finally{
				try {
					is.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public static UploadDownloadUtil getInstance(){
			if(instance == null){
			synchronized(UploadDownloadUtil.class){
				if(instance == null){
					instance = new UploadDownloadUtil();
					try {
						instance.loadProperties();
					} catch (Exception e) {
						throw new RuntimeException(e);
					}
					instance.createDataDirectory();
				}
			}
		}
		return instance;
	}

	public String getConfigValueByKey(String key){
		return this.configProp.getProperty(key.toUpperCase());
	}

	public String getFileFullPath(BusinessDateTO businessDate, String agentId, String fileNameKey){

		return appPath + "/" + getConfigValueByKey(DATA_FOLDER_KEY) + "/" + getFileShortName(businessDate, agentId, fileNameKey);
	}

	public String getFileShortName(BusinessDateTO businessDate, String agentId, String fileNameKey){

		return agentId + "." + fileNameKey + "." + DateUtil.format(businessDate.getBusinessDate(), "yyyyMMdd");
	}
}
